package org.snail;

import com.google.common.collect.Maps;
import org.snail.transport.Connection;
import org.snail.transport.ConnectorDispatcher;

import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;

/**
 * 一个客户端,不同的ip+端口对应不同的Connector
 * Created by fish on 17/8/27.
 */
public class SnailClient {

    /**
     * 连接对象存储 key-value
     */
    private Map<String,Connection> connections = Maps.newConcurrentMap();

    /**
     * 客户端单利分发器
     */
    private ConnectorDispatcher dispatcher = new ConnectorDispatcher();

    private SnailClient(){ }

    public static SnailClient getInstance() {
        return ClientHolder.instance;
    }

    private static class ClientHolder{
        private final static SnailClient instance = new SnailClient();
    }

    /**
     * 当连接启动以后,注册到客户端。
     *
     * @param host
     * @param port
     * @param connection
     */
    public void addConnection(String host,int port,Connection connection){
        connections.put(host+":"+port,connection);
    }

    /**
     * 获取连接。
     *
     * @param host
     * @param port
     */
    public Connection getConnection(String host,int port){
        return connections.get(host+":"+port);
    }

    /**
     * 获取客户端分发器
     */
    public ConnectorDispatcher getDispatcher(){
       return dispatcher;
    }


    /**
     * 临时测试。
     *
     */
    public Connection next(){
        String[] keys = connections.keySet().toArray(new String[0]);
        Random random = new Random();
        String randomKey = keys[random.nextInt(keys.length)];
        Connection connection = connections.get(randomKey);
        return  connection;
    }

}
